package com.fitz.remote.client.pool;

import com.fitz.registry.InstanceInfo;
import com.fitz.remote.client.ConsumerClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fitz
 * Created  on 2020/5/26
 */
public class ConsumerClientPool {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerClientPool.class);

    private static final int WAIT_TIME = 6000;

    GenericObjectPoolConfig poolConfig;

    GenericObjectPool<ConsumerClient> pool;

    private ConsumerClientFactory clientFactory;

    InstanceInfo node;

    public ConsumerClientPool(InstanceInfo node, int minPoolSize, int maxPoolSize) {
        this.node = node;
        poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMinIdle(1);
        poolConfig.setMaxTotal(maxPoolSize);

        clientFactory = new ConsumerClientFactory(node);
        pool = new GenericObjectPool<>(clientFactory,poolConfig);
    }

    public boolean connect(){
        try {
            pool.preparePool();
        } catch (Exception e) {
            logger.error("prepare client connection pool failed.", e);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void close() {
        pool.close();
    }

    public ConsumerClient getClient(){
        try {
            return pool.borrowObject(WAIT_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void returnClient(ConsumerClient client){
        logger.info("return client:{}",client);
        if (client == null){
            return;
        }
        pool.returnObject(client);
    }

    public int getMaxTotal(){
        return pool.getMaxTotal();
    }
    public int getNumIdle(){
        return pool.getNumIdle();
    }
    public int getNumActive(){
        return pool.getNumActive();
    }

}
